<template>
  <view class="tree-item">
    <view class="tree-node" @click="toggleSelect">
      <text v-if="node.children && node.children.length > 0" key="icon" class="icon" @click.stop="toggleExpand">
        {{ expanded ? '▼' : '▶' }}
      </text>
      <view class="node-label">
        <text class="tree-label">{{ node.typeName }}</text>
        <view class="select-icon-wrap" @click.stop="handleNodeClick(node, -1)">
          <SelectStatus :checked="isNodeSelect(node)" />
        </view>
      </view>
    </view>
    <view v-if="expanded && node.children && node.children.length > 0" key="children" class="children">
      <tree-item
        v-for="child in node.children"
        :key="child.typeId"
        :node="child"
        :selected-id="selectedId"
        @update:selected-id="onChildSelect"
      ></tree-item>
    </view>
  </view>
</template>

<script>
import SelectStatus from '@/components/cu-tree-select/components/SelectStatus.vue'

export default {
  name: 'TreeItem',
  components: { SelectStatus },
  props: {
    isExpand: {
      type: Boolean,
      default: false
    },
    node: {
      type: Object,
      required: true
    },
    selectedId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      expanded: false
    }
  },
  watch: {
    isExpand: function (val) {
      if (val) {
        this.expanded = true
      }
    }
  },
  computed: {},
  methods: {
    toggleExpand() {
      this.expanded = !this.expanded
    },
    toggleSelect() {
      // this.$emit("update:selected-id", this.node.typeId);
    },
    onChildSelect(id) {
      this.$emit('update:selected-id', id)
    },
    handleNodeClick(node) {
      // console.log('node', node)
      this.$emit('update:selected-id', this.node.typeId)
    },
    isNodeSelect(node) {
      return node.typeId === this.selectedId
    }
  }
}
</script>

<style scoped>
.tree-item {
  margin-left: 20px;
}
.tree-node {
  display: flex;
  align-items: center;
  cursor: pointer;
  line-height: 45px;
  border-bottom: 1px solid #ccc;
  margin-left: -15px;
}
.icon {
  /*margin-left: 10px;*/
  width: 20px;
  color: #8eb3c3;
}
.children {
  /*margin-left: 20px;*/
}
.node-label {
  width: 100%;
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
}
.tree-label {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}
.select-icon-wrap {
  width: 30px;
}
</style>
